﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ModelBinder.Extension.AspNetCore.FromSmartBody;
using VueShopApi.Common;
using VueShopApi.Dtos;
using VueShopApi.Entities;

namespace VueShopApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RolesController : AuthorizeController
    {
        private readonly ILogger<RolesController> _logger;
        private readonly IFreeSql _context;

        public RolesController(ILogger<RolesController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }


        /// <summary>
        /// 获取所有用户的角色及权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAllRoles()
        {
            var roles = await _context.Select<SpRole>().ToListAsync();

            // SELECT * FROM sp_permission_api as api LEFT JOIN sp_permission as main ON main.ps_id = api.ps_id WHERE main.ps_id is not null
            var permissionKeys = _context.Select<SpPermissionApi, SpPermission>()
                .LeftJoin((api, main) => main.PsId == api.PsId)
                .ToList<PermissionApiIncludePermissionDto>().ToDictionary(p => p.PsId, p => p);

            var list = new List<RoleDto>();
            foreach (var role in roles)
            {
                var rolePermissionIds = role.PsIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(r => Convert.ToInt32(r)).ToList();
                var roleResult = new RoleDto
                {
                    Id = role.RoleId,
                    RoleName = role.RoleName,
                    RoleDesc = role.RoleDesc,
                    Children = GetPermissionsResult(permissionKeys, rolePermissionIds)
                };
                list.Add(roleResult);
            }

            return ServerResponse.Yes(list);
        }

        /// <summary>
        /// 通过角色 ID 获取角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetRole([FromRoute] int id)
        {
            var role = await _context.Select<SpRole>(id).ToOneAsync();
            return ServerResponse.Yes(new
            {
                roleId = role.RoleId,
                roleName = role.RoleName,
                roleDesc = role.RoleDesc,
                rolePermissionDesc = role.PsCa
            });
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="roleDesc"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateRole([FromSmartBody] string roleName, [FromSmartBody] string roleDesc)
        {
            if (string.IsNullOrWhiteSpace(roleName))
                return ServerResponse.BadRequest("角色名称不能为空");
            if (string.IsNullOrWhiteSpace(roleDesc))
                roleDesc = "";

            var role = new SpRole() { RoleName = roleName, RoleDesc = roleDesc, PsIds = "" };
            role.RoleId = (int)await _context.Insert<SpRole>(role).ExecuteIdentityAsync();

            if (role.RoleId == 0)
                return ServerResponse.No("创建角色失败");

            return ServerResponse.Yes(new
            {
                roleId = role.RoleId,
                roleName = role.RoleName,
                roleDesc = role.RoleDesc,
                rolePermissionDesc = role.PsCa
            });
        }

        /// <summary>
        /// 更新角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roleName"></param>
        /// <param name="roleDesc"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateRole([FromRoute] int id, [FromSmartBody] string roleName, [FromSmartBody] string roleDesc)
        {
            var roles = await _context.Update<SpRole>(id).SetDto(new { RoleName = roleName, RoleDesc = roleDesc }).ExecuteAffrowsAsync();
            if (roles > 0)
            {
                var role = await _context.Select<SpRole>(id).ToOneAsync();
                return ServerResponse.Yes(new
                {
                    roleId = role.RoleId,
                    roleName = role.RoleName,
                    roleDesc = role.RoleDesc,
                    rolePermissionDesc = role.PsCa
                });
            }

            return ServerResponse.No("角色ID不存在");
        }

        /// <summary>
        ///   通过角色 ID 进行删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRole([FromRoute] int id)
        {
            await _context.Delete<SpRole>(id).ExecuteAffrowsAsync();
            return ServerResponse.Yes();
        }

        /// <summary>
        /// 对角色进行授权
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rids"></param>
        /// <returns></returns>
        [HttpPost("{id}/Rights")]
        public async Task<IActionResult> SetRoleRight([FromRoute] int id, [FromSmartBody] string rids)
        {
            var roles = await _context.Update<SpRole>(id).SetDto(new { PsIds = rids }).ExecuteAffrowsAsync();
            if (roles > 0)
            {
                var role = await _context.Select<SpRole>(id).ToOneAsync();
                return ServerResponse.Yes(new
                {
                    roleId = role.RoleId,
                    roleName = role.RoleName,
                    roleDesc = role.RoleDesc,
                    rolePermissionDesc = role.PsCa
                });
            }

            return ServerResponse.No("角色ID不存在");
        }

        /// <summary>
        /// 删除角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rightId"></param>
        /// <returns></returns>
        [HttpDelete("{id}/Rights/{rightId}")]
        public async Task<IActionResult> SetManagerRole([FromRoute] int id, [FromRoute] int rightId)
        {
            var role = await _context.Select<SpRole>(id).ToOneAsync();
            if (role == null)
                return ServerResponse.No("角色ID不存在");
            var rightIds = role.PsIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(r => Convert.ToInt32(r)).ToList();
            if (rightIds.Contains(rightId))
                rightIds.Remove(rightId);

            await _context.Update<SpRole>(id).SetDto(new { PsIds = string.Join(",", rightIds) }).ExecuteAffrowsAsync();
            return ServerResponse.Yes(new
            {
                roleId = role.RoleId,
                roleName = role.RoleName,
                roleDesc = role.RoleDesc,
                rolePermissionDesc = role.PsCa
            });
        }
    }
}
